package com.guli.msmservice.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.guli.commonutils.R;
import com.guli.msmservice.bean.EmailCode;
import com.guli.msmservice.service.EmailCodeService;
import com.guli.msmservice.service.MsmService;
import com.guli.msmservice.utils.Msm_Email_Util;
import com.guli.servicebase.exceptionHandler.GuliException;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Locale;
import java.util.concurrent.TimeUnit;

/**
 * @ClassName MsmController
 * @Description TODO
 * @Author YinLiangTao Email:1517535831@qq.com
 * @Date 2022/4/11 23:30
 * @Version 1.0
 */
@RestController
@RequestMapping("/edumsm/msm")
@CrossOrigin
public class MsmController {
    @Resource
    private MsmService msmService;

    @Resource
    private RedisTemplate<String,String> redisTemplate;

    @Resource
    private EmailCodeService emailCodeService;

    @GetMapping("/getNoteWithEmail/{email}")
    public R getNoteWithEmail(@PathVariable("email") String email) throws Exception {
     //先判断redis中是否有验证码
        String code = "";
        //redis
//        code = redisTemplate.opsForValue().get(email);
//        if(!StringUtils.isEmpty(code)){
//            return R.ok();
//        }
        //mysql
        QueryWrapper<EmailCode> wrapper = new QueryWrapper<>();
        wrapper.eq("mobile",email);
        EmailCode one = emailCodeService.getOne(wrapper);
        if(one != null && !StringUtils.isEmpty(one.getCode())){
            System.out.println("验证码已存在********************");
            throw new GuliException(20001,"验证码已存在");
        }
        boolean noteWithEmail = msmService.getNoteWithEmail(email);
        code = Msm_Email_Util.stringBuilder.toLowerCase();
        Msm_Email_Util.stringBuilder = code;
        System.out.println(Msm_Email_Util.stringBuilder+"--------------变小写------------------------");
        if(noteWithEmail){
            //存放在redis中,设置过期时间为5分钟
          //  redisTemplate.opsForValue().set(email,code,5, TimeUnit.MINUTES);

            //存放在mysql数据库中
            EmailCode emailCode = new EmailCode();
            emailCode.setCode(code);
            emailCode.setMobile(email);
            emailCodeService.save(emailCode);
            return R.ok().message("发送短信成功");
        }else{
            return R.error().message("发送短信失败");
        }

    }

}
